/*
 * 该js文件专门用于存放单据通用的方法
 * */
(function () {
	$.get('/flowable/task/getUserTodoTaskCount',function(res){//刷新父节点待办任务
		parent.$('#todoTask').text(res);
	})
	setTimeout(function(){//起始通过cookie判断单据是否流转
		if($.cookie('dhecp_tpTransfer')){
			$.removeCookie('dhecp_tpTransfer',{path:'/'});
			if($('#nid').val()!=0){//如果是制单则无需提示
				$.modal.confirmCom('已保存成功，是否流转该单据？',function(){
		    		layer.closeAll();
		    		tpBtnClick('tpTransfer');
				});
			}
		}
    }, 500);
})();
//表格初始化
function initTable(){
	var th=$(window).height()-$('.north').height()-60<200?'300':'full-' + ( $('.north').height()+60);
	var ev=nid==0?false:true;
	$.tablelist.init({
		elem: '#dhtable'
		,data: dataStr
		,page: false
		,even: gridColumns.readOnly
		,limit: 1000
// 		,initSort: {field: 'iid',type: 'asc'}
		,totalRow: gridColumns.totalRow
   		,cols: [gridColumns.gridBody
		]
		,toolbar: '#toolbar'
		,defaultToolbar: [{title:'列设置',layEvent: 'fieldSet',icon: 'layui-icon-set'}]
		,height:th
		,done:function(res, curr, count){
			listData = table.cache.dhtable;//每次重载都赋值更新表缓存
			selectSelected(dropdownList);//下拉框全部重新赋值
			if(gridColumns.readOnly)readonlyEdit();//只读情况下可编辑
			else setFieldFrontEditList(fieldFrontEditList);//可编辑情况下添加不可编辑背景颜色
			tableDate(res, listData);//日期控件
			showloadings(false);
			detailUpload();
		}
	});
}
//明细表格中的字段遍历
function eachFields(){
	$.each(gridColumns.gridBody,function(i,v){//明细表格中下拉框集合遍历
		if(v.templet)if(v.templet.split("_")[0]=='#dropdown')dropdownList.push(v.field);
	});
	$.each(gridColumns.dictionaryForPageFieldList,function(i,v){//明细表格中不可编辑字段
		if(v.fieldFrontEdit == false && v.fieldFrontHidden == false)fieldFrontEditList.push(v.fields);
	});
	$.each(gridColumns.gridNewLine,function(v,k){//明细新增模板修改默认值
		if(k.substring(0,1)=='#')gridColumns.gridNewLine[v]=$(k).val();
	})
}
//表格不可编辑字段设置背景色，fieldFrontEditList为不可编辑字段field集合
function setFieldFrontEditList(fieldFrontEditList){
	$.each(fieldFrontEditList,function(i,v){
		$(".layui-table-main [data-field='"+v+"']").css('background-color','#F2F2F2');
	});
}
//加载中
function showloadings(t) {
    if (t) {//如果是true则显示loading
        layer.load(2, {
            shade: [0.1, '#000'] //0.1透明度的白色背景
        });
    } else {//如果是false则关闭loading
        layer.closeAll('loading');
    }
}
/*
 * table导入execl
 * param：obj input对象
 * param：tableId 表格ID标识
 * param：importFields 对应导入字段
 * param：listData 表缓存
 * param：moduleTable 模块名称
 * param：decimalObj 表格数据类型字段名及小数位
*FileReader共有4种读取方法：
*1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
*2.readAsBinaryString(file)：将文件读取为二进制字符串
*3.readAsDataURL(file)：将文件读取为Data URL
*4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
*/
function importExcel(obj, tableId, importFields, listData, moduleTable, decimalObj) {
	showloadings(true);
	var wb;//读取完成的数据
	var rABS = false; //是否将文件读取为二进制字符串
	var iid;
	if(!!listData.length)iid=Number(listData[listData.length-1]['iid']);else iid=1;
    if(!obj.files) {
        return;
    }
    const IMPORTFILE_MAXSIZE = 1*2048;       //这里可以自定义控制导入文件大小
    var suffix = obj.files[0].name.split(".")[1]
    if(suffix != 'xls' && suffix !='xlsx'){
        layer.msg('导入的文件格式不正确!')
        return
    }
    if(obj.files[0].size/1024 > IMPORTFILE_MAXSIZE){
    	layer.msg('导入的表格文件不能大于2M')
        return
    }
    var f = obj.files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
        var data = e.target.result;
        if(rABS) {
            wb = XLSX.read(btoa(fixdata(data)), {     //手动转化
                type: 'base64'
            });
        } else {
            wb = XLSX.read(data, {
                type: 'binary'
            });
        }
		var strForm=XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
//		layer.msg(JSON.stringify(strForm));
		if(moduleTable == 'TP_STOCKOFFERPRICE')var fXsFpsl = $("#fXsFpsl").val();
		for(var i=0; i<strForm.length; i++){
			var trData = {};
			$.each(importFields,function(j,v){
				trData[v] = strForm[i][j] ? strForm[i][j] : '';
			})
			trData['iid'] = iid+i;
			if(moduleTable == 'TP_STOCKOFFERPRICE'){
				trData['bPrice'] = trData['bPrice'] ? Number(trData['bPrice']).toFixed(decimalObj.bPrice) : 0;
				trData['bNumb'] = trData['bNumb'] ? Number(trData['bNumb']).toFixed(decimalObj.bNumb) : 0;
				trData['fSumje'] = Number(trData['bPrice'] * trData['bNumb']).toFixed(decimalObj.fSumje);
				if(fXsFpsl){
					trData['fwsdj'] = Number(trData['bPrice'] / (1 + fXsFpsl/100)).toFixed(decimalObj.fwsdj);
					trData['fwsje'] = Number(trData['fSumje'] / (1 + fXsFpsl/100)).toFixed(decimalObj.fwsje);	
				}
			}
			listData.push(trData);
		}
		table.reload(tableId,{data:listData}); 
    };
   if(rABS) {
        reader.readAsArrayBuffer(f);
    } else {
        reader.readAsBinaryString(f);
    }
   
	return true;
}
/*
 * 获取表格数据
 * param：url 数据源
 * param：dataStr 数据存放对象
 * */
function getTableData(url, dataStr){
	$.get(url,function(data){
		if(data.count > 0){
			for(var i=0;i<data.data.length;i++){
				dataStr.push(data.data[i])
			}
		}
	});
}
/*
 * 表格select下拉赋值
 * obj：操作对象
 * param：fieldName 字段名
 * */
function tableSelected(obj, fieldName){
	var selectIndex=obj.tr[0].rowIndex;
	//监听下拉框
	form.on('select(select)', function (obj) {
		var value = obj.value;	//选中的值
		$.each(table.cache.dhtable,function(i,v){
			if(v.LAY_TABLE_INDEX==selectIndex){//缓存表内的下标和当前事件行下标的判断
				v[fieldName]=value;
			}
		}); 
	});
}
/*表格日期控件渲染赋值
 * param:res 表格信息
 * param：listData 表缓存
 */
function tableDate(res, listData){
	$(".layui-input-date").each(function (i) {
		layui.laydate.render({
			elem: this,
			type: 'date',
			trigger: 'click',
			done: function (value, date) {
				var elemtr = $(this.elem).parents('tr').index();
				var elem = $(this.elem).parents('td');
				var datafield = elem.attr("data-field");
				if (res && res.data[elemtr]) {
					listData[elemtr][datafield] = value;
				}
			}
		});
	});
}
/*
 * 表格批量删除行
 * param：tableId 表格ID标识
 * param：listData 表缓存
 * param：checkStatus 表格选中行对象
 * */
function tableDeleteBatch(tableId, listData, checkStatus){
	if(checkStatus.data.length == 0){
		layer.msg("请先选择明细！");
	}else{
		$.modal.confirmCom('确定要删除么？',function(result){
			for(var i=listData.length-1; i>=0; i--){
				if(listData[i]["LAY_CHECKED"]){
					listData.splice(i, 1);    //删除一项
				}
			}
	    	layer.closeAll();
			table.reload(tableId, {data : listData});
	    });
	}
}
/*
 * 单据表头按钮操作
 * param：btnname 按钮标识
 * param：tableData 明细表缓存
 * */
function tpBtnClick(btnname){
	var tabTitleObj = $('.layui-tab-title', parent.document).find('.layui-this').find('span');//当前tab对象
	var tabName = tabTitleObj.html();
	if(btnname == 'tpPrev' || btnname == 'tpNext'){						//前单、后单
		if(btnname == 'tpPrev'){
			var getDataUrl = moduleUrl+'/lastnid?nid='+nid;
		}else{
			var getDataUrl = moduleUrl+'/nextnid?nid='+nid;
		}
		$.operate.get(getDataUrl, function(res){
			if(res.code == 0){
				res.data = JSON.parse(res.data);
				tabName = tabName.replace($("#bid").val(),res.data.bid);
				tabName = tabName.replace(' - 新增','('+res.data.bid+')');
				tabTitleObj.html(tabName);
				window.location.href = moduleUrl+'/edit?nid='+res.data.nid;
			}
		})
	}else if(btnname == 'tpAdd'){										//单据新增
		if(tabName.substring(tabName.length-2,tabName.length)!='新增')tabName=tabName.split('(')[0]+' - 新增';
		tabTitleObj.html(tabName);
		goUrl(moduleUrl+'/edit?nid=0');
	}else if(btnname == 'tpSave'){										//单据保存
		var tableData=(typeof table=='undefined')?(noTable.length>0?noTable:[{'nid':0}]):table.cache.dhtable;//没有定义table以及为制单状态时则默认为[{'nid':0}]
		var is_return = 0,judge_fields,must_field={},inputForm = $(".head-form");
        headData = inputForm.serializeFormToJson();
//        $.each(b_fields,function(k,v){//特殊处理：页脚隐藏字段的数值类型
//        	if(v.fieldType=='decimal(19,6)')headData[v.fields]=Number(headData[v.fields]);
//        });
        
		if(typeof table=='undefined')judge_fields=k_fields.concat(t_fields);//判断必填字段：静态表格(表头加页脚隐藏字段)
		else judge_fields=k_fields;
	    $.each(judge_fields,function (fk,fv) {
	    	if(moduleTable == 'TCRM_BUSINESSINFO' && $("#"+fv.fields+"_div").css('display') === 'none'){return true;}  //商机信息存在前端切换商机类型隐藏，需特殊处理过滤必填字段
	        if(fv.fieldFrontRequired && !fv.fieldFrontHidden)must_field[fv.fields] = fv.fieldName + " 不能为空";//遍历必填且不隐藏的字段
	    })
	    $.each(must_field,function (k,v) {
	        if(!inputForm.find("#"+k).val()){
	            layer.msg(v);
	            is_return = 1;
	            if(!typeof table=='undefined')inputForm.find("#"+k).css('border','1px solid red');
	            inputForm.find("#"+k).focus();
	            return false;
	        }
	    })
	    if(is_return)return false;
	    //没有明细并且为新增状态
	    if(tableData.length == 0 && nid == 0){
    		layer.msg('单据明细 不能为空');
	    	is_return = 1;
	    }
	    if(is_return)return false;
	    //判断明细必填
	    if(tableData.length > 0 ){
		    $.each(tableData, function(ti, tv){
		    	var lineNum = ti+1;
				$.each(gridColumns.fieldRequiredList, function(tmi, tmv){
					if(!tv[tmv]){
						layer.msg('明细第 '+ lineNum +' 行 '+gridColumns.fieldNameRequiredList[tmi]+' 不能为空');
						is_return = 1;
						return false;
					}
					if(is_return)return false;
		    	});
				if(is_return)return false;
		    });
	    }
		if(is_return)return false;
		if(typeof beforeSave=='function')tableData=beforeSave(tableData);//判断该页面是否有点击保存之前的函数
	    var postData = {'infoMap':JSON.stringify(headData),'infoItems':JSON.stringify(tableData)};//转化为json字符串格式
	    $.operate.post(moduleUrl+'/editpost', postData, function(res){
	        if(res.code == 0){
	        	if(nid==0)$.operate.get(moduleUrl+'/lastnid?nid=0', function(res2){//当为新增单据时，获取新增保存单据的bid，改变标题
					if(res2.code == 0){
						res2.data = JSON.parse(res2.data);
						tabName = tabName.replace(' - 新增','('+res2.data.bid+')');
						tabTitleObj.html(tabName);
					}
				})
	        	if(typeof noTable=='undefined' && table.cache.dhtable.length==0){//删除单据时
	        		tabName=tabName.split('(')[0]+' - 新增';
					tabTitleObj.html(tabName);
	        	}
	        	$.cookie('dhecp_tpTransfer', 1, { expires: 1, path: '/' });//保存成功后存放流转cookie
	        	goUrl(moduleUrl+'/edit?nid='+res.data);
	        }
	    });
	}else if(btnname == 'tpTransfer' || btnname == 'tpReturn' || btnname == 'tpReject'){//流转、退回、驳回
        var headData = $(".head-form").serializeFormToJson(),title,toUrl;
        var infoMap=JSON.stringify(headData);
		if(btnname == 'tpTransfer'){
			toUrl = moduleUrl+'/flowpage?fType=flow_go';
			title='流转页面';
		}else if(btnname == 'tpReturn'){
			toUrl = moduleUrl+'/flowpage?fType=flow_back';
			title='退回页面';
		}else if(btnname == 'tpReject'){
			toUrl = moduleUrl+'/flowpage?fType=flow_reject';
			title='驳回页面';
		}
		$.post(toUrl,{'infoMap':infoMap}, function(res){
        	if(res.code==0){
        		$.modal.open(title, res.data, 800, 700, function(index){
                    var result = window["layui-layer-iframe" + index].processTaskCallback();
        			if(result){
        				$('.layui-layer-btn0').attr('style','display:none');
        				$.operate.save(result.url, result.data,function(res){
        					if(res.code==0){
        	                    layer.closeAll();
        	                    layer.msg(res.msg,{icon:1});
        						setTimeout(function(){
        				            window.location.reload();
        		                }, 1000);
        					}else{
        						layer.closeAll();
        						$.modal.msgError(((result == undefined)?"操作错误！":result.msg), modal_status.FAIL);
        					}
        				});
        			}
                });
        	}else{
        		$.operate.ajaxSuccess(res);
        	}
		})
	}else if(btnname == 'tpReset'){//重置
        toUrl = moduleUrl+'/flowbackpost';
        if(nid==0){
			$.modal.msgError('制单环节不需要重置！', icon = 2);
		}else{
			$.modal.confirmCom('是否将单据重置到初始状态？',function(){
				$.post(toUrl,{'tableDataId':nid,'optType':'reset'},function(res){
		        	if(res.code==0){
		        		$.operate.ajaxSuccess(res);
						setTimeout(function(){
				            window.location.reload();
		                }, 1000);
		        	}else{
						layer.closeAll();
						$.modal.msgError(((res == undefined)  ? "操作错误！" : res.msg), modal_status.FAIL);
		        	}
				})
			});
		}
	}else if(btnname == 'tpDelete'){//删除
		$.modal.confirmCom('是否删除该单据？',function(){
			if(nid==0){
				$.modal.msgError('新增单据无需删除！',{icon:2});
			}else{
				var postData = {'infoMap':JSON.stringify($(".head-form").serializeFormToJson()),'infoItems':JSON.stringify([])};
			    $.operate.post(moduleUrl+'/editpost', postData, function(res){
			        if(res.code == 0){
		        		tabName=tabName.split('(')[0]+' - 新增';
						tabTitleObj.html(tabName);
			        	goUrl(moduleUrl+'/edit?nid='+res.data);
			        }
			    });
			}
		});
	}
}
/*
 * 验证表格编辑
 * param：editObj 当前编辑对象值、字段名、所在行的所有相关数据  
 * param：decimalObj 表格数据类型字段名及小数位
 * */
function checkEdit(editObj, decimalObj){
	var decimalNum = decimalObj[editObj.field];
	if(decimalNum > -1){
		if($.common.isNumber(editObj.value)){
			return Number(editObj.value).toFixed(decimalNum);
		}else{
			layer.msg('请填写正确数值！')
			return false;
		}
	}
}
/*
 * 验证表格编辑
 * param：editObj 当前编辑对象值、字段名、所在行的所有相关数据  
 * param：decimalObj 表格数据类型字段名及小数位
 * */
function getDecimalNum(fields, decimalObj){
	var decimalNum = decimalObj[fields];
	if(decimalNum > -1){
		return decimalNum;
	}else{
		return false;
	}
}
/*
 * 通过dom给表格渲染值
 * param：layID 表格ID标识
 * param：dataIndex 行号
 * param：dataField 字段名
 * param：data 赋值
 * */
function setTableValue(layID, dataIndex, dataField, data,type){
	if(type==null)$("[lay-id="+layID+"]").find("[data-index="+dataIndex+"]").find("[data-field="+dataField+"]").children().html(data);
	else $("[lay-id="+layID+"]").find("[data-index="+dataIndex+"]").find("[data-field="+dataField+"]").find(type).html(data);
}
/*
 * 调入数据处理
 * param：obj 调入对象
 * */
function relationIn(obj){
	$.modal.open(obj.text, "/common/relation/relationpage?relationguid="+obj.getAttribute('value'),'1100','700', function(index){
	    var res = window["layui-layer-iframe" + index].callbackdata();
	    if(res.dataStr.length==0){
	    	layer.msg("无数据，请选择！");
	    }else{
	    	var flag=true,copyHead;
	    	$.each(res.bFieldKeys,function(k,v){//主键列判断调入数据是否重复
	    		$.each(table.cache.dhtable,function(k2,v2){
	    			$.each(res.dataStr,function(k3,v3){
	    				if(v3[k]==v2[v])flag=false;
	    			});
	    		});
	    	});
	    	if(flag){
	    		$.each(res.headFields,function(k,v){//调入数据的单据表头字段判断重复
		    		$.each(res.dataStr,function(k2,v2){
		    			if(k2!=0 && res.dataStr[0][v]!=v2[v])flag=false;
			    	});
		    	});
		    	if(flag){
		    		$.each(res.headFields,function(k,v){//调入数据和明细中数据的单据表头字段判断重复
		    			$.each(res.dataStr,function(k2,v2){
			    			if(listData.length!=0 && $('#'+k).val()!=v2[v])flag=false;
				    	});
			    	});
		    		if(flag){
		    			$.each(res.headFields,function(k,v){//表头赋值
				    		$('#'+k).val(res.dataStr[0][v]);
				    	})
				    	var newListData=[];
			    		$.each(res.dataStr,function(k,v){
			    			var newData={};
			    			$.each(gridColumns.gridNewLine,function(k3,v3){//不能直接赋值到newData，只能一个个属性添加，否则会重复调入
			    				newData[k3]=v3;
			    			});
			    			$.each(res.gridFields,function(k2,v2){
			    				newData[k2]=v[v2];
			    			});
			    			if(!!listData.length)newData['iid']=Number(listData[listData.length-1]['iid'])+k+1;else newData['iid']=1+k;
			    			newListData.push(newData);
				    	})
				    	newListData = calcDetail(newListData);//调入数据计算
			    		listData.push.apply(listData,newListData);
				    	table.reload('dhtable', {data : listData});
				        layer.close(index);
				    }else{
		    			layer.msg("调入数据中与单据表头不一致，请重新选择！可能的冲突为："+Object.values(res.headFieldNames));
		    		}
		    	}else{
		    		layer.msg(Object.values(res.headFieldNames)+"存在不唯一，请重新选择！");
		    	}
	    	}else{
	    		layer.msg('单据中已有相同明细，请重新选择！');
	    	}
	    }
	});
}
//调入数据计算
function calcDetail(rowData){
	var sl=$("#fXsFpsl").val()?$("#fXsFpsl").val():$("#fCgFpSl").val();//优先取表头的税率
	for(var i = 0; i < rowData.length; i++){
		if(!sl)sl=rowData[i]['fXsFpsl']?rowData[i]['fXsFpsl']:(rowData[i]['fCgFpSl']?rowData[i]['fCgFpSl']:null);//表头没有税率则取明细的税率
		rowData[i]['fSumje'] = rowData[i]['fSumje']?rowData[i]['fSumje']:Number((rowData[i]['bNumb']?rowData[i]['bNumb']:0) * (rowData[i]['bPrice']?rowData[i]['bPrice']:0)).toFixed(decimalObj.fSumje);
		rowData[i]['fWsDj'] = rowData[i]['fWsDj']?rowData[i]['fWsDj']:Number((rowData[i]['bPrice']?rowData[i]['bPrice']:0) / (1 + sl/100)).toFixed(decimalObj.fWsDj);
		rowData[i]['fWsJe'] = rowData[i]['fWsJe']?rowData[i]['fWsJe']:Number(rowData[i]['fSumje'] / (1 + sl/100)).toFixed(decimalObj.fWsJe);
		rowData[i]['fSe'] = rowData[i]['fSe']?rowData[i]['fSe']:Number(rowData[i]['fSumje'] - rowData[i]['fWsJe']).toFixed(decimalObj.fSe);
		rowData[i]['fCgZk'] = rowData[i]['fCgZk']?rowData[i]['fCgZk']:Number(rowData[i]['bPrice'] / rowData[i]['fHsMj']).toFixed(decimalObj.fCgZk);
	}
	return rowData
}
//表格编辑——资金计算
function moneyCalculation(){
	table.on('edit(ftable)', function(obj){
		var selector = obj.tr.selector+' td[data-field="'+obj.field+'"] div';
        var oldtext = $(selector).text();// 单元格编辑之前的值
		var editField = obj.field,//编辑单元格fieId
			editRow = obj.data,//编辑单元格行数据
			dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
			isReturn,editValue;
		if(decimalObj[obj.field] > -1){//判断是否数值字段
			editValue = checkEdit(obj, decimalObj);//判断输入是否为数值，否则还原数值
			if(!editValue){
				editValue = oldtext;
				listData[dataindex][editField] = oldtext;
				isReturn = 1;
			}
			if(!isReturn){//输入的是数值并且改单元格是数值格式字段
				var fXsFpsl = $("#fXsFpsl").val()?$("#fXsFpsl").val():listData[dataindex]['fXsFpsl'];//销售税率
				if(!fXsFpsl)fXsFpsl = $("#fCgFpSl").val()?$("#fCgFpSl").val():listData[dataindex]['fCgFpSl'];//采购税率
				if(editField == 'iid'){//行号
					listData[dataindex]['iid'] = Number(editValue).toFixed(decimalObj.iid);
				}else if(editField == 'fBjzk'){//报价折扣
					listData[dataindex]['bPrice'] = Number(editValue * listData[dataindex]['fHsMj']).toFixed(decimalObj.bPrice);//单价
					listData[dataindex]['fSumje'] = Number((listData[dataindex]['bNumb']?listData[dataindex]['bNumb']:0)*listData[dataindex]['bPrice']).toFixed(decimalObj.fSumje);//合同金额
					obj.update({bPrice: listData[dataindex]['bPrice'],fSumje: listData[dataindex]['fSumje']});
				}else if(editField == 'bPrice'){//单价
					listData[dataindex]['fBjzk'] = Number(listData[dataindex]['fHsMj'])?Number(editValue/listData[dataindex]['fHsMj']).toFixed(decimalObj.fBjzk):0;
					listData[dataindex]['fHtzk'] = Number(listData[dataindex]['fHsMj'])?Number(editValue/listData[dataindex]['fHsMj']).toFixed(decimalObj.fHtzk):0;
					obj.update({fBjzk:listData[dataindex]['fBjzk'],fHtzk: listData[dataindex]['fHtzk']});
				}else if(editField == 'fHtzk'){//合同折扣
					listData[dataindex]['bPrice'] = Number(editValue*(listData[dataindex]['fHsMj']?listData[dataindex]['fHsMj']:0)).toFixed(decimalObj.bPrice);
					obj.update({bPrice:listData[dataindex]['bPrice']});
				}
				if(editRow.bPrice && editRow.bNumb){//单价、数量都存在，重新计算
					listData[dataindex]['fSumje'] = Number(listData[dataindex]['bPrice'] * listData[dataindex]['bNumb']).toFixed(decimalObj.fSumje);//合同金额
					listData[dataindex]['fWsDj'] = Number(listData[dataindex]['bPrice']/(1 + fXsFpsl/100)).toFixed(decimalObj.fWsDj);//未税单价
					listData[dataindex]['fWsJe'] = Number(listData[dataindex]['fSumje'] / (1 + fXsFpsl/100)).toFixed(decimalObj.fWsJe);//未税金额
					listData[dataindex]['fSe'] = Number(listData[dataindex]['fSumje']-listData[dataindex]['fWsJe']).toFixed(decimalObj.fSe);//税额
					obj.update({fSumje: listData[dataindex]['fSumje'],fWsJe: listData[dataindex]['fWsJe'],fWsDj:listData[dataindex]['fWsDj'],fSe:listData[dataindex]['fSe']});
				}
				if(editField == 'bPrice'){//实际进价的计算（隐藏时实时更新，显示时为空赋值）
					$.each(gridColumns.gridBody,function(i,v){
						if(v.field=='fPrice'){
							if(v.hide=="true")listData[dataindex]['fPrice'] = Number(editValue).toFixed(decimalObj.fPrice);
							else{
								if(!editRow.fPrice)listData[dataindex]['fPrice'] = Number(editValue).toFixed(decimalObj.fPrice);
							}
							obj.update({fPrice: listData[dataindex]['fPrice']});
						}
					})
				}
				if(listData[dataindex]['bPrice'] && listData[dataindex]['gPrice']!=null && listData[dataindex]['bNumb']){//单价、成本价、数量==>单项毛利
					listData[dataindex]['fDxMl']=Number(listData[dataindex]['bNumb'] * (listData[dataindex]['bPrice']-listData[dataindex]['gPrice'])).toFixed(decimalObj.fDxMl);//单项毛利
					obj.update({fDxMl: listData[dataindex]['fDxMl']});
				}
			}
			setTableValue('dhtable', dataindex, editField, editValue,'input');
			$("[lay-id='dhtable']").find("[data-index="+dataindex+"]").find("[data-field="+editField+"]").find("input").val(editValue);//格式化当前编辑框
			listData[dataindex][editField] = editValue;
		}
	});
}
//监听排序事件——重载赋值渲染
function monitorSort(){
	table.on('sort(ftable)', function(obj){
		table.reload('dhtable', {
			initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
			,done: function(res, curr, count){
		    	listData = table.cache.dhtable;
				selectSelected(dropdownList);
				if(!gridColumns.readOnly)setFieldFrontEditList(fieldFrontEditList);
				tableDate(res, listData);//日期控件
				showloadings(false);
				detailUpload();
				}
		  });
	});
}
//下拉可编辑——报价税率
function changeFpsl(lx){
	form.on('select('+lx+'_select)', function (data) {//选择移交单位 赋值给input框
        $("#"+lx).val(Math.round(data.value));
		form.render();//修复下拉框选中后无法消失的问题
//		$("#fXsFpsl_select").next().find("dl").css({ "display": "none" });
        updatefWsDj(Math.round(data.value));//更新未税单价
    });
	window.refreshSelect=function(){//失去焦点
        form.render();//修复下拉框选中后无法消失的问题
	}
    window.inputSearch = function () {
    	$("#"+lx).val(Math.round($("#"+lx).val()));
        var value = $("#"+lx).val();
        $("#"+lx+"_select").val(value);
        form.render();
        $("#"+lx+"_select").next().find("dl").css({ "display": "block" });
        var dl = $("#"+lx+"_select").next().find("dl").children();
        var j = -1;
        for (var i = 0; i < dl.length; i++) {
            if (dl[i].innerHTML.indexOf(value) <= -1) {
                dl[i].style.display = "none";
                j++;
            }
            if (j == dl.length-1) {
                $("#"+lx+"_select").next().find("dl").css({ "display": "none" });
            }
        }
    }
    $("#"+lx).change(function(){
    	updatefWsDj( $("#"+lx).val());				//更新未税单价
    })
}
//更新税率——资金计算
function updatefWsDj(fXsFpsl){
	showloadings(true);
	var fWsDj,fWsJe,fSe;
	for(var i = 0; i < listData.length; i++){
		fWsDj = listData[i]['fWsDj'] = Number((listData[i]['bPrice']?listData[i]['bPrice']:0) / (1 + fXsFpsl/100)).toFixed(decimalObj.fWsDj);
		fWsJe = listData[i]['fWsJe'] = Number((listData[i]['fSumje']?listData[i]['fSumje']:0) / (1 + fXsFpsl/100)).toFixed(decimalObj.fWsJe);
		fSe = listData[i]['fSe'] = Number((listData[i]['fSumje']?listData[i]['fSumje']:0)-listData[i]['fWsJe']).toFixed(decimalObj.fSe);
		setTableValue('dhtable', i, 'fWsDj', fWsDj);
		setTableValue('dhtable', i, 'fWsJe', fWsJe);
		setTableValue('dhtable', i, 'fSe', fSe);
	} 
	showloadings(false);
}
//表格初始化之前的动作集合
function beforeInit(){
	if(nid==0){//制单时字段默认值初始赋值
		$.each(all_fields,function(i,k){
			if(k.fieldFrontValue){
				if(k.fieldFrontValue.substring(0,1)=='#')$('#'+k.fields).val($(k.fieldFrontValue).val());
				else $('#'+k.fields).val(k.fieldFrontValue);
			}
		})
	}else{
	    if(gridColumns.readOnly)$.each(k_fields,function(i,k){
	    	if(k.fieldExceptEdit && buttonState['tp-save']=='enable'){
	    		$('#'+k.fields).removeClass('canntEdit');
	    		$('#'+k.fields)[0].readOnly=false;
	    	}
	    })
	}
	//遍历表头字段——下拉框赋值、时间控件渲染
	$.each(k_fields,function(k,v){//表头下拉框的隐藏框初始赋值
		if(v.fieldFrontType=="t_dropdown"){
			if(v.fieldFrontSave!=v.fieldFrontShow){
				if(!!v.fieldMatched)$('#'+v.fieldMatched).val($('#'+v.fields).val());
			}
		}
		if(v.fieldFrontType=="t_date" || v.fieldFrontType=="t_datetime"){//表头时间控件渲染
			laydate.render({elem:'#'+v.fields,type:v.fieldFrontType.substring(2,v.fieldFrontType.length),trigger:'click'});
		}
	});
	//监听表头下拉框事件——下拉框联动
	form.on('select(select)',function(e){
		if(e.elem.dataset['fieldfrontsave']!=e.elem.dataset['fieldfrontshow']){
			if(!!e.elem.dataset['fieldmatched'])$('#'+e.elem.dataset['fieldmatched']).val(e.value);
		}
	});
	//查询流程
	$('.layui-icon-search').click(function(){
		if(!!$('#procInstId').val()){
			var width = 800;
			var height = ($(window).height() - 150);
			var url = "/flowable/process/processSpeed/"+ $('#procInstId').val();
			layer.open({
				type: 2,
				area: [width + 'px', height + 'px'],
				offset: '10%',//距离顶部10%
				fix: false,
				//不固定
				maxmin: true,
				shade: 0.6,
				title: "流程跟踪",
				content:  url,
				btn: ['关闭'],
				//点击弹层外区域关闭
				shadeClose: true,
				cancel: function(index) {
					return true;
				}
			});
		}else{
			var url = "/flowable/definition/flowsheetbykey?procDefKey="+moduleTable;
			var width = 800;
			var height = ($(window).height() - 150);
			layer.open({
				type: 2,
				area: [width + 'px', height + 'px'],
				offset: '10%',//距离顶部10%
				fix: false,
				//不固定
				maxmin: true,
				shade: 0.6,
				title: "流程图",
				content:  url,
				btn: ['关闭'],
				//点击弹层外区域关闭
				shadeClose: true,
				cancel: function(index) {
					return true;
				}
			});
		}
	})
}
//只读情况下可编辑
function readonlyEdit(){
	if(gridColumns.readOnly){
		$.each(gridColumns.dictionaryForPageFieldList,function(i,v){
			if(v.fieldExceptEdit && buttonState['tp-save']=='enable')$('thead').find('th[data-field='+v.fields+']').attr('style','background-color:#ffe48d');
		})
	}
}
//导入数据
function importListExcel(obj, importFields, mName) {
	showloadings(true);
	var wb;//读取完成的数据
	var rABS = false; //是否将文件读取为二进制字符串
	var iid;
    if(!obj.files) {
        return;
    }
    const IMPORTFILE_MAXSIZE = 1*2048;       //这里可以自定义控制导入文件大小
    var suffix = obj.files[0].name.split(".")[1]
    if(suffix != 'xls' && suffix !='xlsx'){
        layer.msg('导入的文件格式不正确!')
        return
    }
    if(obj.files[0].size/1024 > IMPORTFILE_MAXSIZE){
    	layer.msg('导入的表格文件不能大于2M')
        return
    }
    var f = obj.files[0];
    var reader = new FileReader();
    var reStr='';
    reader.onload = function(e) {
        var data = e.target.result;
        if(rABS) {
            wb = XLSX.read(btoa(fixdata(data)), {     //手动转化
                type: 'base64'
            });
        } else {
            wb = XLSX.read(data, {
                type: 'binary'
            });
        }
		var strForm=XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
		var listData = [], tNum = tStr = trStr='';
		hasNull = false;
		for(var i=0; i<strForm.length; i++){
			var trData = {};
			tNum = i+1;
			trStr += '<tr><td style="text-align: center;">' + tNum + '</td>';
			$.each(importFields,function(j,v){
				tStr = strForm[i][j] ? strForm[i][j] : '';
				if(mName != "product"){
					if($.inArray(v,dateFiled) > -1){
						tStr = tStr ? forDate(tStr) : '';
					}
				}
				
				$.each(filedRequired,function(r,rv){
					if(v == r && tStr == '')hasNull = true;				//导入数据必填字段有空值
				})
				trStr += '<td tindex="' + i + '" tfield="' + v + '">' + tStr + '</td>';
				trData[v] = tStr;
			})
			trStr += '</tr>';
			trData['iid'] = tNum;
			listData.push(trData);
		}
		if(hasNull)layer.alert("导入数据必填字段有空值！请核对数据，重新导入。", {icon:7});
		$("#itbody").html(thStr + trStr);
		intable(listData, mName);
    };
   if(rABS) {
        reader.readAsArrayBuffer(f);
    } else {
        reader.readAsBinaryString(f);
    }
	return true;
}
/*弹出层（导入列表内容）
 * mName：product产品;customer客户;provider供应商;
 */
function intable(listDataObj, mName){
	if(mName == 'product'){
		var dTitle = '导入产品列表'; 
	}else if(mName == 'customer'){
		var dTitle = '导入客户列表'; 
		var stepNameMsg = '请选择客户属性！';
	}else if(mName == 'provider'){
		var dTitle = '导入供应商列表'; 
		var stepNameMsg = '请选择供应商属性！';
	}
	layer.open({
		type: 1,
		area: ['800px', '500px'],
		fix: false,
		offset: '10%',
		maxmin: true,
		shade: 0.3,
		title: dTitle,
		content: $('#iTable').html(),
		btn: ['<i class="fa fa-check"></i> 确定', '<i class="fa fa-remove"></i> 取消'],
		shadeClose: true,
		zIndex: 1001,
		success: function(layero, index){
			showloadings();
			form.render();
		},
		btn1: function(index, layero){
			if(mName == 'customer' || mName == 'provider'){
				cID = $(".layui-layer-page .cid").val();
				if(!cID){layer.msg("请选择所属公司！", {icon:7});return false;}
				
				bUser = $(".layui-layer-page .bUser").val();
				bDept = $(".layui-layer-page .bDept").val();
				if(!bUser){layer.msg("请选择所属员工！", {icon:7});return false;}
				stepName = $(".layui-layer-page [name='stepName']").val();
				
				if(!stepName){layer.msg(stepNameMsg, {icon:7});return false;}
			}
			if(hasNull){
				layer.alert("导入数据必填字段有空值！请核对数据，重新导入。", {icon:7});
				return false;
			}
			showloadings(1);
			$("#importProgress").css('display','table-column');
			$(".importProgress").css('display','table-column');
			var importObj = [], 
			inum = 0, 
			onetime = 1, 
			flag = 1, 
			oneImportNum = 2, 						//默认一次导入条数
			allImportNum = listDataObj.length, 		//数据总量
			importBl = 0	//导入进度
			times = 0;		//请求次数
			if(mName == 'product')$.operate.post("/business/product/cleanproductimportpost"); 		//清除导入旧数据
			element.progress('dhprogress', '0%');
			setTimeout(function(){
    			if(allImportNum > 9 && allImportNum <= 100){
    				oneImportNum = 5;
    			}else if(allImportNum > 100 && allImportNum <= 500){
    				oneImportNum = 30;
    			}else if(allImportNum > 500 && allImportNum <= 1000){
    				oneImportNum = 50;
    			}else if(allImportNum > 1000){
    				oneImportNum = 100;
    			}
    			times = Math.ceil(allImportNum/oneImportNum);			
    			eachImport(listDataObj, 0, oneImportNum, allImportNum, times, 1);return false;
			}, 1000);
		}
	});
}
//结束导入，关闭弹出层
function closeProcess(res, mName){
	setTimeout(function(){
		$("#importProgress").css('display','none');
		$(".importProgress").css('display','none');
		layer.closeAll();
		$.operate.ajaxSuccess(res);
		
		$(".search-field").each(function(i,v){				//当前显示的查询字段(包含.search-field)
			wherestr[v.name]=''
		});
		//动态获取条件的值
		$.each(wherestr,function(i,v){
			if((i.substring(i.length-2,i.length)=='_s' || i.substring(i.length-2,i.length)=='_e') && $("#"+i).attr('fft') != 't_text'){
				if(!$("#"+i.substring(0,i.length-2)).val())wherestr[i]="";
				return;//时间控件的衍生字段需跳出循环
			}
			var vs=$("[name="+i+"]").val();
			switch($("#"+i).attr('fft')){
				case 't_checkcondition':
					if($("#"+i).prop("checked")){
						wherestr[i] = 1;
					}else{
						wherestr[i]='';
					}
				break;
				case 't_radio':
					if($("[name='"+i+"']:checked").val()){
						wherestr[i] = $("[name='"+i+"']:checked").val()
					}else{
						wherestr[i]='';
					}
					break;
				case 't_date':
					wherestr[i+'_s']="";
					wherestr[i+'_e']="";
					if($("#"+i).attr('ffct')=='t_between' && !!$("#"+i).val()){//区间范围的需要切割，而且尾头多出了空格
						var st=vs.split('~');
						wherestr[i+'_s']=st[0].substring(0,st[0].length-1);
						wherestr[i+'_e']=st[1].substring(1,st[1].length);
					}else{
						vs?wherestr[i]=vs:wherestr[i]='';
					}
					break;
				case 't_datetime':
					wherestr[i+'_s']="";
					wherestr[i+'_e']="";
					if($("#"+i).attr('ffct')=='t_between' && !!$("#"+i).val()){//区间范围的需要切割，而且尾头多出了空格
						var st=vs.split('~');
						wherestr[i+'_s']=st[0].substring(0,st[0].length-1);
						wherestr[i+'_e']=st[1].substring(1,st[1].length);
					}else{
						vs?wherestr[i]=vs:wherestr[i]='';
					}
					break;
				default:
					vs?wherestr[i]=vs:wherestr[i]='';
					break;
			}
		});
		
		
		if(mName == 'product')wherestr['vCpFl'] = vCpFl;
        table.reload('dhtable', {page: {curr: 1},where:wherestr});
	},1500);
}
/*
 * 单据表头弹出框
 * parma:fields 目标字段
 * parma:tindex 单据明细中的下标
 * parma:fieldName 目标字段名
 * parma:fieldSearchType 待选数据类型
 */
function getMore(fields,tindex,fieldName,fieldSearchType){
	// console.log(fields,tindex,fieldName,fieldSearchType);
	var obj = $(this),flag = true, 
		gClient = $("#gClient").val()||(tindex?table.cache.dhtable[tindex-1].gClient:null),
		gProvider=$("#gProvider").val()||(tindex?table.cache.dhtable[tindex-1].gProvider:null);
	if(fieldSearchType && fieldSearchType!='undefined'){//存在待选数据类型
		if(fieldSearchType.split('_')[1]=='baseinfo'){//基础数据选择
			var mTitle = '选择'+fieldName, 
				mUrl = '/base/baseinfo/select?vtype='+fieldSearchType.split('_')[2];
		}else{
			switch(fieldSearchType.split('_')[1]){
				case 'companyinfo':
					var mTitle = '选择'+fieldName, mUrl = '/base/company/select';
					break;
				case 'depotinfo':
					var mTitle = '选择'+fieldName, mUrl = '/system/depot/select?deleted=0';
					break;
				case 'userinfo':
					var mTitle = '选择'+fieldName, mUrl = '/system/user/userselect?pagetype=radio', mWidth = '560', mHeight = '465';
					break;
				case 'roleinfo':
					var mTitle = "选择"+fieldName, mUrl = "/system/role/select", mWidth = "500", mheight = "400";
					break;
				default:
					flag=false;
					layer.msg('该待选数据类型未处理！',{icon:7});
					break;
			}
		}
	}else{//无待选数据类型，特殊处理的弹出框
		switch(fields){
			case 'gCName':
				var mTitle = '选择客户', mUrl = '/crm/customer/select?blxr=1';
				if(moduleUrl=='/business/offerprice')mUrl='/crm/customer/select?stepNameMark=2&blxr=1';//销售报价需要查询除黑名单以外客户
				break;
			case 'vMan'://联系人
			case 'vKhLxr'://联系人
			case 'vLxr'://联系人
			case 'gUserName'://销售员
				if(gClient){
		    		if(fields == 'vMan' || fields == 'vKhLxr' || fields == 'vLxr'){
		            	var mTitle = '选择客户联系人', mUrl = '/crm/customerpersion/select?gClient='+gClient;  
		    		}else if(fields == 'gUserName'){
		    			var mTitle = '选择销售员', mUrl = '/crm/customer/userselect?gClient='+gClient;
		    		}
		    	}else{
		    		flag = false;
		    		layer.msg("请先选择客户！",{icon:7});
		    	}
				break;
			case 'gPName':
				var mTitle = '选择供应商', mUrl = '/crm/provider/select?blxr=1';
				break;
			case 'vPMan'://联系人
			case 'pUserName'://采购员
				if(gProvider){
					if(fields == 'vPMan'){
		            	var mTitle = '选择供应商联系人', mUrl = '/crm/providerpersion/select?gprovide='+gProvider;  
		    		}else if(fields == 'pUserName'){
		    			var mTitle = '选择采购员', mUrl = '/crm/provider/userselect?gprovide='+gProvider;
		    		}
				}else{
					flag=false;
					layer.msg("请先选择供应商！",{icon:7});
				}
				break;
			case 'htBid':
				var mTitle = '选择销售合同', mUrl = '/business/bargainin/select';
				break;
			case 'vXmMc':
				var mTitle = '选择项目', mUrl = '/business/projectadded/select';
				if($('#gCName').val())mUrl = '/business/projectadded/select?gCName='+$('#gCName').val();
				break;
			case 'zpXqBid':
				var mTitle = '选择招聘需求表', mUrl = '/hr/recruitmentapply/select';
				break;
			case 'gwBid':
			case 'gwSmBid':
				var mTitle = '选择岗位说明书', mUrl = '/hr/positioninstructions/select';
				break;
			case 'msPjBid':
				var mTitle = '选择面试评价表', mUrl = '/hr/interviewresults/select';
				break;
			case 'rzXxBid':
				var mTitle = '选择入职信息登记表', mUrl = '/hr/personnelrzxx/select';
				break;
			case 'vXmBm':
				var mTitle = '选择项目编码', mUrl = '/business/projectcode/select';
				break;
			default:
				flag=false;
				layer.msg('该特殊弹出框未处理！',{icon:7});
				break;
		}
	}
    if(flag){
	    $.modal.open(mTitle, mUrl, mWidth, mHeight, function(index){
	        var res = window["layui-layer-iframe" + index].callbackdata();
	        if(res=="none" || !res){//没有选中时
            	layer.msg("请选择！", {icon:7});
            }else{
    	        // console.log(res);
        		var fieldsList={};//目标字段及数据源字段对象
            	if(!!tindex){//明细中的弹出框
            		$.each(gridColumns.gridBody, function(i, v){//循环表格字段
            			if(v.fieldMatched==fields || v.field==fields){
            				fieldsList[v.field]=v.fieldFrontSave;
            				$.each(gridColumns.gridBody, function(i2, v2){//第二次循环，判断联动
            					if(v2.fieldMatched==v.field){
            						fieldsList[v2.field]=v2.fieldFrontSave;
            					}
        					});
            			}
            		});
            		$.each(fieldsList,function(i,v){//直接通过dom修改而不再重载
            			listData[tindex-1][i]=res[v];
            			if(i==fields)setTableValue('dhtable', tindex-1, i, res[v],'span');
            			else setTableValue('dhtable', tindex-1, i, res[v]);
            		});
            	}else{//表头中的弹出框
            		var eachFields=(typeof all_fields == 'undefined')?gridColumns.dictionaryForPageFieldList:all_fields;
                	$.each(eachFields, function(i, v){
            			if(v.fieldMatched==fields || v.fields==fields){
            				fieldsList[v.fields]=v.fieldFrontSave;
            				$.each(eachFields, function(i2, v2){//第二次循环，判断联动
            					if(v2.fieldMatched==v.fields){
            						fieldsList[v2.fields]=v2.fieldFrontSave;
            						$.each(eachFields, function(i3, v3){//第三次循环，判断联动
                    					if(v3.fieldMatched==v2.fields){
                    						fieldsList[v3.fields]=v3.fieldFrontSave;
                    					}
                					});
            					}
        					});
            			}
            		});
            		$.each(fieldsList, function(i, v){//表头联动赋值
            			$("#"+i).val(res[v]);
            		});
            		// console.log(fieldsList);//联动字段对象
            	}
    	        layer.close(index);
            }
	    });
    }
}
//选择公司、员工（导入页）
function getMoreForImport(type){
	var flag = true;
	switch(type){
		case 'company':
			var mTitle = '选择公司', mUrl = '/base/company/select';
			break;
		case 'user':
			var mTitle = '选择员工', mUrl = '/system/user/userselect?pagetype=radio', mWidth = '560', mHeight = '465';
			break;
		default:
			flag=false;
			layer.msg('该待选数据类型未处理！');
			break;
	}
	if(flag){
	$.modal.open(mTitle, mUrl, mWidth, mHeight, function(index){
        var res = window["layui-layer-iframe" + index].callbackdata();
		switch(type){
		case 'company':
			$(".layui-layer-page .cid").val(res.vId);
			$(".layui-layer-page .cidName").val(res.vName);
			$(".layui-layer-page .cidName").attr('title',res.vName);
			break;
		case 'user':
			$(".layui-layer-page .bUser").val(res.userId);
			$(".layui-layer-page .bDept").val(res.deptPath);
			$(".layui-layer-page .bUserName").val(res.userName);
			break;
		}
		form.render();
	    layer.close(index);
	});
	}
}

